<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>图书列表</title>
		<link rel="stylesheet" href="layui/css/layui.css"/>
		<style>
			/* 图片自适应，需要改变max-height */
			.table-image{
				max-width: 100%;
				max-height: 25px;
				height: auto;
				object-fit: contain;
			}
		</style>
	</head>
	<body>
		
		<h1 style="text-align: center;color: #16baaa; margin-top: 10px; margin-bottom: 10px;">图书列表</h1>
		<div class="layui-container">
			<form class="layui-form layui-row layui-col-space16">
			  <div class="layui-col-md2">
			    <div class="layui-input-wrap">
			      <input type="text" name="bookName" placeholder="bookName" class="layui-input" lay-affix="clear">
			    </div>
			  </div>
			  <div class="layui-col-md2">
			    <div class="layui-input-wrap">
			       <div id="categoryId" class="xm-select-demo"></div>
			    </div>
			  </div>
			  <div class="layui-col-md2">
			    <div class="layui-input-wrap">
			      <select name="status">
					<option value="">上架/下架</option>
				    <option value="1">上架</option>
				    <option value="0">下架</option>
				  </select>
			    </div>
			  </div>  
			  <div class="layui-col-md3">
			    <div class="layui-input-wrap">
			      <input type="text" class="layui-input" id="ID-laydate-range-year" name="time" placeholder="请选择时间">
			    </div>
			  </div>  
			  <div class="layui-col-md3">
			    <button class="layui-btn" lay-submit lay-filter="search">查询</button>
			    <button type="reset" id='reset' class="layui-btn layui-btn-primary">重置</button>
			  </div>  			  
			</form>
		</div>		
		<table class="layui-hide" id="book-list-id" lay-filter="book-list-filter"></table>
		
		<script src="layui/layui.js"></script>
		<script src="js/xm-select.js"></script>
		<script>
			layui.use(function(){
				let table = layui.table;
				let layer = layui.layer;
				let $ = layui.$;
				let laydate = layui.laydate;
				let form = layui.form;
				
				form.on('submit(search)', function(obj){
					let time = obj.field.time;
					if(time && time.length>0){
						let times = time.split("-");
						if(times && times.length==2){
							obj.field.start=times[0];
							obj.field.end=times[1];
						}
					}
					table.reload('book-list-id', {
						page: {
							curr: 1
						},
						where: obj.field
					});
					return false;
				});
				
				$.getJSON("http://127.0.0.1:8080/getCategoryList", function(data){
					if(data.code==0){
						let select = xmSelect.render({
							el: '#categoryId',
							data: data.data,
							prop: {
								name: 'categoryName',
								value: 'categoryId'
							},
							radio: true,
							filterable: true,
							name: 'categoryId'
						});
						
						// reset
						$('#reset').click(function(){
							select.setValue([ ]);
						});
					}else{
						layer.msg('获取图书种类失败');
					}
				});
				
				laydate.render({
					elem: '#ID-laydate-range-year',
					type: 'datetime',
					range: true,
					format: 'yyyy/MM/dd HH:mm:ss'
				});
				
				table.on('toolbar(book-list-filter)', function(obj){
					let event = obj.event;
					if(event=='batchDelete'){
						let checkStatus = table.checkStatus(obj.config.id);
						let data = checkStatus.data;
						if(data && data.length>0){
							layer.confirm('确定要删除这些数据吗？', {btn: ['确定', '取消']}, function(index){		
								let bookIds = [];
								// 这里用for (let var1 in var2)不行？？？
								for (let i = 0; i < data.length; i++) {
									bookIds.push(data[i].bookId);
								}
								$.ajax({
									type: 'post',
									url: 'http://127.0.0.1:8080/batchDeleteBook',
									data: JSON.stringify(bookIds),
									contentType: 'application/json',									
									dataType: 'json',
									success: function(d){
										if(d.code==0){
											layer.msg('删除成功');
											table.reload('book-list-id');
										}else{
											layer.msg(d.msg);
										}
									}
								});
								layer.close(index);
							})
						}else{
							layer.msg('未选中任何行');
						}
					}else if(event=='add'){
						layer.open({
							type: 2,
							title: '添加图书',
							content: 'book-add.html',
							area: ['500px', '620px'],
							skin: 'layui-layer-molv',
							end: function(){
								table.reload('book-list-id');
							}
						});
					}
				});
				
				// table.on('tool(book-list-filter)', function(obj)这里不加#
				table.on('tool(book-list-filter)', function(obj){
					let event = obj.event;
					if(event=='delete'){
						// let index = layer.confirm('确定要删除这条数据吗？', {btn: ['确定', '取消']}, function()这样也能获取弹出层的index
						layer.confirm('确定要删除这条数据吗？', {btn: ['确定', '取消']}, function(index){
							let bookId = obj.data.bookId;
							// {bookId: bookId}这里key不加""
							$.getJSON("http://127.0.0.1:8080/deletaBookByBookId", {bookId: bookId}, function(data){
								if(data.code==0){
									layer.msg('删除成功');
									// table.reload("book-list-id")这里不加#
									table.reload("book-list-id");	
								}else{
									layer.msg(data.msg);
								}
							})
							layer.close(index);
						})
					}else if(event=='edit'){
						layer.open({
							type: 2,
							title: '编辑图书',
							content: 'book-edit.html',
							area: ['500px', '620px'],
							skin: 'layui-layer-molv',
							end: function(){
								table.reload('book-list-id');
							},
							// 回显
							success: function(layero, index, that){
								// 这样做可以回显普通文字，但不能回显下拉框和select等
								// 回显下拉框和select有两种方法，一是通过content: 'book-edit.html?categoryId=&status='这样传过去，book-edit获取URL之后获取categoryId和status
								// 第二种方式是通过postMessage(跨文档通信)传递参数
								// let body = layer.getChildFrame('body', index);
								// body.find('#bookId').val(obj.data.bookId);
								// body.find('#bookName').val(obj.data.bookName);
								// body.find('#authorName').val(obj.data.authorName);
								// body.find('#price').val(obj.data.price);
								// body.find('#createTime').val(obj.data.createTime);
								// body.find('#bookAddress').val(obj.data.bookAddress);
								// body.find('#bookUrl').val(obj.data.bookUrl);
								// body.find('#ID-upload-demo-preview').find('img').attr('src', "http://127.0.0.1:8080"+obj.data.bookUrl)
								let iframeWindow = window[layero.find('iframe')[0].name];
								iframeWindow.postMessage(obj.data);
							}
						});
					}
				});
				
				table.render({
					elem: '#book-list-id',
					url: 'http://127.0.0.1:8080/getBooksByParams',
					// page: true,
					page: {
						limit: 5,
						limits: [5, 10, 15, 20],
						groups: 3,
						prev: '上一页',
						next: '下一页',
						// theme: '#1e9fff'
					},
					request: {
						pageName: 'pageNo',
						limitName: 'pageSize'
					},
					parseData: function(res){
						return {
							'code': res.code,
							'msg': res.msg,
							'count': res.data.total,
							'data': res.data.page
						}
					},
					// ``之间可以写多行String
					toolbar: `
						<div>
							<button type="button" class="layui-btn layui-btn-sm layui-bg-red" lay-event="batchDelete">批量删除</button>
							<button type="button" class="layui-btn layui-btn-sm" lay-event="add">添加</button>
						</div>
					`,
					cols: [[
						{
							type: 'checkbox',
							fixed: 'left'
						},
						{
							title: 'bookId',
							field: 'bookId'
						},
						{
							title: 'bookName',
							templet: function(d){
								return '<img class="table-image" src="http://127.0.0.1:8080'+d.bookUrl+'">';
							}
						},
						{
							title: 'bookUrl',
							field: 'bookName'
						},
						{
							title: 'authorName',
							field: 'authorName'
						},
						{
							title: 'price',
							field: 'price',
							sort: true
						},
						{
							title: 'categoryId',
							templet: function(d){
								return d.category.categoryName;
							}
						},
						{
							title: 'createTime',
							field: 'createTime'
						},
						{
							title: 'status',
							templet: function(d){
								return d.status==1?'<span class="layui-badge layui-bg-green">上架</span>':'<span class="layui-badge">下架</span>';
							}
						},
						{
							title: '操作',
							templet: function(d){
								let s = '<button type="button" class="layui-btn layui-btn-xs" lay-event="edit">更新</button>';
								s += '<button type="button" class="layui-btn layui-btn-xs layui-bg-red" lay-event="delete">删除</button>'
								return s;
							}
						}
					]]
					
				});
			});
		</script>
	</body>
</html>
